<!DOCTYPE html>
<html class="x-admin-sm">
<head>
    <meta charset="UTF-8">
    <title>宇成建筑</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" href="../statics/css/font.css">
    <link rel="stylesheet" href="../statics/plugins/layui/css/layui.css">
    <link rel="stylesheet" href="../statics/css/xadmin.css">
    <link rel="stylesheet" href="../statics/css/style.css">
    <style>
        .layui-table td, .layui-table th {
            min-width: 40px !important;
        }

        .layui-table td, .layui-table th {
            padding: 5px !important;
        }

        th:first-child, td:first-child {
            text-align: center;
        }
    </style>
</head>

<body class='labelAuto'>
<div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="welcome.html">首页</a>
            <a href="javascript:;">施工管理</a>
            <a href="javascript:;">施工分账</a>
            <a class="areaName" href="javascript:;"></a>
            <a class="sectionName" href="javascript:;"></a>
            <a href="javascript:;">施工分账记录</a>
            <a>
                <cite><span class="groupName"></span> 施工量价编辑</cite>
            </a>
        </span>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right"
       onclick="location.reload()" title="刷新">
        <i class="layui-icon layui-icon-refresh" style="line-height:30px"></i>
    </a>
    <a class="layui-btn layui-btn-small" style="line-height:1.6em;margin-top:3px;float:right;margin-right:10px"
       onclick="window.history.go(-1)" title="后退">
        <i class="iconfontBlod" style="line-height:30px">&#xe74f;</i>
    </a>
</div>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <h2 style="text-align: center">班组施工项分账记录表</h2>
                    <form class="layui-form" style="overflow: scroll;">
                        <table class="layui-table" id="lists" lay-filter="test" style="min-width:1350px;">
                            <thead>
                            <tr>
                                <th style="width:50px;text-align: center">编号</th>
                                <th style="width:180px">施工项</th>
                                <th style="width:80px">工程量</th>
                                <th style="width:90px">单位</th>
                                <th style="width:80px">单价</th>
                                <th style="width:90px">总价</th>
                                <th style="width:100px">完成时间</th>
                                <th style="width:360px">备注</th>
                                <th style="width:70px">录入批次</th>
                                <th style="width:60px">录入人</th>
                                <th style="width:70px">状态</th>
                                <th style="width:90px">操作</th>
                            </tr>
                            </thead>
                            <tbody></tbody>
                            <tfoot class="layui-table-total">
                            <tr>
                                <th>合计</th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th id="total"></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                                <th></th>
                            </tr>
                            </tfoot>
                        </table>
                    </form>
                </div>
                <div class="layui-card-body layui-row">
                    <div class="layui-col-md4"></div>
                    <div class="layui-col-md4" style="text-align: center">
                        <button class='save layui-btn' data-save="0" id='saveTmp'>临时保存</button>
                        <button class='save layui-btn' data-save="1" id='saveOne'>保存</button>
                    </div>
                    <div class="layui-col-md4"></div>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script src="../statics/plugins/layui/layui.js" charset="utf-8"></script>
<script src='../statics/plugins/jQuery-3.2.1/jquery-3.2.1.min.js'></script>
<script type="text/javascript" src="../statics/plugins/X-admin/xadmin.js"></script>
<script type="text/javascript" src="../statics/js/public.js?v=1129"></script>
<script type="text/javascript">
    layui.use(['form', 'layer', "table", "laydate"], function () {
        var form = layui.form;
        var layer = layui.layer;
        var laydate = layui.laydate;
        $('form').css('height', (window.innerHeight - 165) + 'px');
        var projectId = getParam('projectId');
        var sectionId = getQueryString('sectionId');
        var areaId = getQueryString('areaId');
        var professionId = getQueryString('professionId');
        var groupId = getQueryString('groupId');
        var batch = getQueryString('batch');
        var areaName = localStorage.getItem('areaName');
        var sectionName = localStorage.getItem('sectionName');
        var groupName = localStorage.getItem('groupName');
        $('.layui-breadcrumb a.areaName').html(areaName);
        $('.layui-breadcrumb a.sectionName').html(sectionName);
        $('.layui-breadcrumb span.groupName').html(groupName);

        var option = '<option value="">请选择施工项</option>';
        $.ajax({
            url: url + '/setting/assignment/lists',
            type: 'post',
            async: false,
            data: {
                professionId: professionId,
                token: getToken()
            },
            dataType: 'json',
            success: function (r) {
                for (var l = 0; l < r.data.data.length; l++) {
                    option += `
                        <option value='${r.data.data[l].id}' name=${r.data.data[l].unitName}>${r.data.data[l].name}</option>
                    `
                }
            }
        });

        var data = [];//保存后台传回来的分账数据
        $.ajax({
            url: url + "/project/project/groupAssignment",
            type: "POST",
            async: false,
            data: {
                projectId: projectId,
                sectionId: sectionId,
                professionId: Number(professionId),
                groupId: Number(groupId),
                batch: batch,
                token: getToken()
            },
            success: function (r) {
                data = r.data
            }
        });
        var tableHtml = '';
        var total = 0;
        for (let i = 0; i < data.length; i++) {
            total += Number(data[i].totalPrice);
            if (data[i].status == 1 || data[i].status == 2){
                tableHtml += `<tr data-id=${data[i].id}>
                            <td class="index">${i + 1}</td>
                            <td>${data[i].assignmentName == null ? "" : data[i].assignmentName}</td>
                            <td>
                                ${numberFormat(data[i].amount)}
                            </td>
                            <td>${data[i].unitName == null ? "" : data[i].unitName}</td>
                            <td>
                                ${numberFormat(data[i].price, 'currency')}
                            </td>
                            <td class="totalPrice" data-total=${data[i].totalPrice}>
                                ${numberFormat(data[i].totalPrice, 'currency')}
                            </td>
                            <td>
                                ${data[i].completeTime ? data[i].completeTime.substr(0, 10) : ''}
                            </td>
                            <td>
                                ${data[i].remark === 'null' ? '' : data[i].remark}
                            </td>
                            <td>
                                ${data[i].batch === 0 ? '未保存' : data[i].batch}
                            </td>
                            <td>
                                ${data[i].adminName ? data[i].adminName : ''}
                            </td>
                            <td>${approvalStatus(data[i].status)}</td>
                            <td>
                                ${data[i].status != 1 && data[i].status != 2 ? "<button class='remove layui-btn layui-btn-danger' type='button'>删除</button>" : ''}
                            </td>
                        </tr>`
            }else{
                tableHtml+=`<tr class="new" data-id='${data[i].id}'>
                        <td class="index">${i + 1}</td>
                        <td><select name="assignmentId" data-id="${data[i].assignmentId}" lay-search>${option}</select></td>
                        <td><input class="layui-input" type='number' name='amount' min="0" value="${Number(data[i].amount)}">
                        </td>
                        <td>${data[i].unitName == null ? "" : data[i].unitName}</td>
                        <td><input class="layui-input" type='number' name='price' min="0" value="${Number(data[i].price)}"></td>
                        <td class="totalPrice" data-total="${data[i].totalPrice}"><input class="layui-input" type='number' name='totalPrice' min="0" value="${Number(data[i].totalPrice)}" readonly></td>
                        <td>${data[i].completeTime.substr(0, 10)}</td>
                        <td><textarea class='layui-input' name="remark">${data[i].remark === 'null' ? '' : data[i].remark}</textarea>
                        </td>
                        <td>${data[i].batch === 0 ? '未保存' : data[i].batch}</td>
                        <td>${data[i].adminName ? data[i].adminName : ''}</td>
                        <td>${approvalStatus(data[i].status)}</td>
                        <td>${data[i].status != 2 && data[i].status != 3 ? "<button class='remove layui-btn layui-btn-danger' type='button'>删除</button>" : ''}</td>
                    </tr>`
            }
        }
        $('tbody').append(tableHtml);
        if (batch == 0 || batch == ''){
            $('tbody').append(blankCol());
        }

        $('tbody tr').each(function(){
            let assignmentId = $(this).find('select[name=assignmentId]').data('id');
            if (assignmentId !=''){
                $(this).find(`select[name=assignmentId] option[value=${assignmentId}]`).prop('selected', 'selected');
            }
        });
        form.render();
        $('#total').empty().html(numberFormat(total, 'currency'));


        //备注的文本域，自动调整适应段落高度
        $('body').on('input', 'textarea', function () {
            this.style.height = 'auto';
            this.style.height = this.scrollHeight + "px";
        });

        form.on('select', function (data) {
            var name = $(data.elem).find('option:selected').attr('name');
            if (name == 'null') {
                name = "";
            }
            $(data.elem).parent().next().next().html(name);
        });

        $('body').on('input propertychange', 'tbody tr td input', function () {
            var tmp = $(this).parent().parent().find('input[name=amount]').val() * $(this).parent().parent().find('input[name=price]').val();
            $(this).parent().parent().find('input[name=totalPrice]').val(Math.floor(tmp*100)/100);
            $(this).parent().parent().find('td.totalPrice').data('total',tmp);
            totalPrice();
        });

        function blankCol() {
            let index = $('tbody tr').length;

            return `<tr class="new" data-id=''>
                        <td class="index">${index + 1}</td>
                        <td><select name="assignmentId" data-id="" lay-search>${option}</select></td>
                        <td><input class="layui-input" type='number' name='amount' min="0">
                        </td>
                        <td></td>
                        <td><input class="layui-input" type='number' name='price' min="0"></td>
                        <td class="totalPrice" data-total=""><input class="layui-input" type='number' name='totalPrice' min="0" readonly></td>
                        <td></td>
                        <td><textarea class='layui-input' name="remark"></textarea>
                        </td>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td><button class='clickBtn layui-btn' type="button"><i class="layui-icon layui-icon-add-1"></i></button></td>
                    </tr>`
        }

        //插入新一行
        $('body').on('click', '.clickBtn', function () {
            $('tbody').append(blankCol());
            $('tr.new:not(:last-child) td:last-child').empty().html(`<button class='remove layui-btn layui-btn-danger' type="button">删除</button>`)
            form.render();
        });

        //删除当前行
        $('body').on('click','button.remove',function(){
            let id = $(this).parent().parent().data('id');
            if (id != ''){
                layer.open({
                    type: 1,
                    title: "删除",
                    area: ["40%", '30%'],
                    content:`
                        <form class="layui-form layerOpen" action="">
                            <div class="layui-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label">确定删除吗？</label>
                                </div>
                            </div>
                        </form>
                    `,
                    btn: ['确定','取消'],
                    skin: 'my-skin',
                    yes:function(){
                        $.ajax({
                            url: url + '/project/project/delAssignment',
                            type: 'post',
                            data: {
                                id: id,
                                token: getParam('token')
                            },
                            async: false,
                            dataType: 'json',
                            success: function (r) {
                                tips('删除',r);
                                setTimeout(function(){
                                    layer.closeAll()
                                })
                            }
                        })
                    }
                })
            }
            //移除当前行
            $(this).parent().parent().remove();
            //更新index
            let index = $('tbody tr').length;
            $('td.index').each(function(i){
                $(this).empty().html(i+1)
            })
        });

        $('body').on('click', '.save', function () {
            var save = $(this).data('save');
            var data = [];
            for (var i = 0; i < $('tbody tr.new').length; i++) {
                var list = {
                    assignmentId: 0,
                    amount: 0,
                    price: 0,
                    totalPrice: 0,
                    remark: ''
                };
                list.id = Number($('tbody tr.new').eq(i).data('id'));
                list.assignmentId = Number($('tbody tr.new').eq(i).find('select:first option:selected').val());
                list.amount = Number($('tbody tr.new').eq(i).find('input[name=amount]').val());
                list.price = Number($('tbody tr.new').eq(i).find('input[name=price]').val());
                list.totalPrice = Number($('tbody tr.new').eq(i).find('input[name=totalPrice]').val());
                list.remark = $('tbody tr.new').eq(i).find('textarea[name=remark]').val();
                if (list.assignmentId === 0) {
                    continue;
                } else {
                    data.push(list);
                }
            }
            if (data.length === 0) {
                layer.msg('请确认施工分账信息是否填写完整!');
            } else {
                $.ajax({
                    type: 'post',
                    url: url + '/project/project/addAssignment',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({
                        data: data,
                        projectId: projectId,
                        areaId: getQueryString('areaId'),
                        sectionId: sectionId,
                        professionId: professionId,
                        groupId: groupId,
                        save: save,
                        token: getToken()
                    }),
                    beforeSend:function(){
                        $('button.save').addClass('layui-btn-disabled')
                    },
                    success: function (r) {
                        if (r.code == 100000) {
                            tips('添加施工项', r);
                            setTimeout(function () {
                                if (save=== 0){
                                    layer.closeAll();
                                    location.reload();
                                }else{
                                    window.location.href=`workmanAssignmentLog.html?sectionId=${sectionId}&projectId=${projectId}&areaId=${areaId}`
                                }
                            }, 1000)
                        } else {
                            tips('添加施工项', r);
                        }
                    },
                    complete:function(){
                        $('button.save').removeClass('layui-btn-disabled')
                    }
                });
            }
        });

        function totalPrice () {
            let totalPrice = 0;
            $('td.totalPrice').each(function(){
                totalPrice += Number($(this).data('total'))
            });
            $('th#total').empty().html(numberFormat(totalPrice, 'currency'))
        };

    });
</script>

</html>